<template>
  <view class="add-address">
    <!-- 导航栏 -->
    <Header :title="title"></Header>

    <!-- 表单 -->
    <view class="card">
      <view class="form-item">
        <label for="">姓名</label>
        <input type="text" placeholder="收货人姓名" v-model="addressForm.name">
      </view>
      <view class="form-item">
        <label for="">电话</label>
        <input type="number" placeholder="收货人手机号" v-model="addressForm.tel">
      </view>
      <view class="form-item">
        <label for="">地区</label>
        <pickerAddress @change="changeAreaHandler"><text class="picker"
            :style="addressForm.area.indexOf('选择')===0?'color:#808080':''">{{addressForm.area}}</text>
        </pickerAddress>
      </view>
      <view class="form-item">
        <label for="">详细地址</label>
        <input type="text" placeholder="街道门牌楼层房间号等信息" v-model="addressForm.addressDetail">
      </view>
      <view class="form-item none-border">
        <label for="">邮政编码</label>
        <input type="number" placeholder="邮政编码" v-model="addressForm.postalCode">
      </view>
    </view>
    <view class="card">
      <!-- 设置默认-->
      <view class="form-item none-border set_default">
        <text>设为默认收货地址</text>
        <switch @change="switchChangeHandler" :checked="addressForm.isDefault" color="#0c34ba" />
      </view>
    </view>
    <!-- 按钮-->
    <view class="save" @click="AddressHandler">
      保存地址
    </view>
    <view class="save del" v-show="title==='编辑地址'" @click="deleteAddressHandler">
      删除
    </view>
  </view>

</template>

<script>
  import Header from "../../../../../components/HeaderNav/HeaderNav.vue"
  import pickerAddress from "../../../../../components/wangding-pickerAddress/wangding-pickerAddress.vue"
  import {
    req
  } from "../../../../utils/request/request";
  import {
    uniToast
  } from "../../../../utils/uni/uni";
  import {
    mapActions
  } from 'vuex'
  export default {
    components: {
      Header,
      pickerAddress,
    },
    data() {
      return {
        title: "新增地址",
        aid: "",
        sids: '',
        addressForm: {
          name: "jirawu",
          area: "广东省/广州市/南沙区",
          postalCode: "455211",
          addressDetail: "455211",
          tel: "15818854192",
          isDefault: false
        },
      };
    },
    onLoad(opts) {
      this.title = opts.title || "新增地址"
      this.aid = opts.aid || ""
      opts.aid && this.queryAddressByAid(opts.aid)
      this.sids = opts['sids']
    },
    methods: {
      ...mapActions('user', ['getAddress']),
      /* 获取地址详细信息 */
      queryAddressByAid(aid) {
        req('findAddressByAid', {
          reqData: {
            aid,
          },
          isToken: true
        }).then(({
          data: res
        }) => {
          const data = res['result'][0]
          data['area'] = data['province'] + '/' + data['city'] + '/' + data['county']
          data['isDefault'] = data['isDefault'] ? true : false
          this.addressForm = {
            ...this.addressForm,
            ...data
          }
        }, err => {
          console.log(err);
        })
      },
      /* 收货地址操作*/
      AddressHandler() {
        if (!this.aid) {
          this.addAddressHandler()
        } else {
          this.editAddressHandler(this.aid)
        }
      },
      /* 添加收货地址 */
      addAddressHandler() {
        let {
          name,
          tel,
          area,
          addressDetail,
          postalCode,
          isDefault
        } = this.addressForm
        const formData = {
          name,
          tel,
          isDefault: isDefault ? 1 : 0,
          addressDetail,
          postalCode,
          areaCode: postalCode,
        }
        area = area.split('/')
        formData.province = area[0]
        formData.city = area[1]
        formData.county = area[2]
        req('addAddress', {
          reqData: formData,
          isToken: true,
          method: 'POST'
        }).then(({
          data: res
        }) => {
          if (res['code'] === 9000) {
            uniToast(res['msg'])
            this.timer = setTimeout(() => {
              !this.toUrl ? this.backOrder() : uni.navigateBack()
            }, 500)
            return
          }
          uniToast(res['msg'], "error")
        }, err => {
          console.log(err);
        })
      },
      backOrder() {
        this.getAddress(0)
        uni.navigateTo({
          url: '/pages/order/order?sids=' + this.sids,
        });
      },
      /* 删除收货地址 */
      deleteAddressHandler() {
        req('deleteAddress', {
          reqData: {
            aid: this.aid
          },
          isToken: true,
          method: 'POST'
        }).then(({
          data: res
        }) => {
          if (res['code'] === 10000) {
            this.timer = setTimeout(() => {
              uni.navigateBack()
            }, 500)
          }
          uniToast(res['msg'])
        }, err => {
          console.log(err);
        })
      },

      /* 修改收货地址 */
      editAddressHandler(aid) {
        let {
          name,
          tel,
          area,
          addressDetail,
          postalCode,
          isDefault
        } = this.addressForm
        const formData = {
          aid,
          name,
          tel,
          isDefault: isDefault ? 1 : 0,
          addressDetail,
          postalCode,
          areaCode: postalCode,
        }
        area = area.split('/')
        formData.province = area[0]
        formData.city = area[1]
        formData.county = area[2]
        req('editAddress', {
          reqData: formData,
          isToken: true,
          method: 'POST'
        }).then(({
          data: res
        }) => {
          uniToast(res['msg'])
          if (res['code'] === 30000) {
            this.timer = setTimeout(() => {
              uni.navigateBack()
            }, 500)
          }
        }, err => {
          console.log(err);
        })
      },
      /* 选择默认地址 */
      switchChangeHandler(e) {
        const val = e['detail']['value']
        this.$set(this.addressForm, 'isDefault', val)
      },
      changeAreaHandler(data) {
        this['addressForm']['area'] = data['data'].join('/')
      }
    }
  }
</script>

<style lang="scss" scoped>
  page {
    background-color: #f7f7f7;
  }

  .add-address {
    .card {
      // border-top-right-radius: 15rpx;
      // border-top-left-radius: 15rpx;
      border-radius: 15rpx;
      overflow: hidden;
      margin: 30rpx;
      padding: 0 20rpx;
      background-color: #fff;

      .form-item {
        height: 100rpx;
        border-bottom: 1rpx solid #ddd;
        display: flex;
        align-items: center;
        position: relative;

        &.none-border {
          border-bottom: 0 solid #ddd;
        }

        .forward {
          position: absolute;
          right: 0;
        }

        label {
          width: 150rpx;
          font-size: 24rpx;
        }

        .picker {
          display: inline-block;
          width: 480rpx;
        }

        .picker,
        input {
          flex: 1;
          padding-right: 10rpx;
          font-size: 24rpx;
        }
      }

      .set_default {
        font-size: 24rpx;
        display: flex;
        justify-content: space-between;
      }
    }

    .save {
      background-color: #0c34ba;
      color: #fff;
      margin: 30rpx;
      border-radius: 50rpx;
      display: flex;
      justify-content: center;
      align-items: center;
      font-size: 24rpx;
      height: 80rpx;
      margin-top: 100rpx;

      &.del {
        margin-top: 20rpx;
        background-color: #fff;
        color: #333;
      }
    }
  }
</style>
